package com.ft.service;


import com.ft.config.OrderStateMachineConfiguration;
import com.ft.mapper.OrderMapper;
import com.ft.model.Order;
import com.ft.model.enums.OrderStatusChangeEventEnum;
import com.ft.statemachine.recipes.persist.PersistEnumStateMachineHandler;
import com.ft.statemachine.recipes.persist.PersistEnumStateMachineHandler.PersistEnumStateChangeListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;

/**
 * @author: zhangjianghua
 * @Date: 2018-10-10 10:53
 */
public class OrderStateService {
    private final PersistEnumStateMachineHandler handler;
    private final PersistEnumStateChangeListener listener;

    @Autowired
    private OrderMapper orderMapper;

    public OrderStateService(PersistEnumStateMachineHandler handler,PersistEnumStateChangeListener listener) {
        this.handler = handler;
        this.listener = listener;
        this.handler.addPersistStateChangeListener(listener);
    }

    public boolean change(Long orderId, OrderStatusChangeEventEnum event) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        Message<OrderStatusChangeEventEnum> message = MessageBuilder.withPayload(event)
                .setHeader("stateMachine", OrderStateMachineConfiguration.orderStateMachine)
                .setHeader("primaryKey", order.getId()).build();
        return handler.handleEventWithState(message, order.getStatus());
    }

}
